<template>
  <div style="margin-top: 40px">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px" class="demo-ruleForm">
      <el-form-item label="任务类型：" prop="taskType">
        <el-radio-group v-model="ruleForm.taskType">
          <el-radio-button :label="1">拍照打卡</el-radio-button>
          <el-radio-button :label="2">扫描二维码</el-radio-button>
          <el-radio-button :label="3">摄像头识别</el-radio-button>
          <el-radio-button :label="4">线上答题</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="任务名称：" prop="taskName">
        <el-input v-model="ruleForm.taskName" placeholder="请输入任务名称"></el-input>
      </el-form-item>
      <el-form-item label="任务优先级" prop="isMainQuest">
        <el-radio-group v-model="ruleForm.isMainQuest">
          <el-radio label=1>主线任务</el-radio>
          <el-radio label=2>支线任务</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="有效日期：" required prop="dateRange">
        <el-col :span="11">
          <div class="block">
            <el-date-picker
                v-model="ruleForm.dateRange"
                type="datetimerange"
                :picker-options="pickerOptions"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right">
            </el-date-picker>
          </div>
        </el-col>
      </el-form-item>
      <el-form-item label="任务标签：" prop="taskLabel">
        <el-input v-model="ruleForm.taskLabel" placeholder="请输入任务标签"></el-input>
      </el-form-item>
      <el-form-item label="任务流程：" prop="taskSequence" >
        <el-button @click="addDomain" icon="el-icon-circle-plus-outline" >新增流程</el-button>
      </el-form-item>
      <el-form-item
          v-for="(domain, index) in ruleForm.taskSequence"
          :label="'第' + (index + 1) + '步'"
          :key="domain.key"
          :prop="'domains.' + index + '.value'"
      >
        <el-row type="flex" justify="space-between">
          <el-col :span="8">
            <el-input v-model="domain.value" style="width: 420px;" type="textarea"></el-input>
          </el-col>
          <el-col :span="4">
            <el-tooltip class="item" effect="dark" content="刪除" placement="right">
              <el-button type="danger" icon="el-icon-delete" circle plain
                         @click.prevent="removeDomain(domain)" style="margin-left: 32px;margin-top: 10px"></el-button>
            </el-tooltip>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="积分获得：" prop="pointsAwarded">
        <el-input-number v-model="ruleForm.pointsAwarded"  :step="1" min="0" controls-position="right"></el-input-number>
      </el-form-item>
      <el-form-item label="徽章获得：" prop="badgeAwarded">
        <el-cascader
            v-model="ruleForm.badgeAwarded"
            placeholder="请选择获得徽章" clearable
            :options="badgeList"
            :props="{ expandTrigger: 'hover' }"></el-cascader>
      </el-form-item>
      <el-form-item label="属性增量：" prop="attributesAwarded">
        <!--{"人脉": 5, "勇气": 5, "幸运": 5, "智慧": 0, "魅力": 0, "健康值": 0, "学习力": 0, "道德值": 0}-->
        <el-descriptions class="margin-top" :column="4" style="margin-top: 5px" border>
          <el-descriptions-item label=" 人脉" label-class-name="my-label" class-name="my-content" align="center">
            <el-input-number v-model="ruleForm.connectionAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label=" 勇气" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.courageAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="幸运" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.luckyAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="智慧" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.wisdomAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label=" 魅力" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.charmAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="健康值" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.healthAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="学习力" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.learningAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
          <el-descriptions-item label="道德值" align="center" label-class-name="my-label" class-name="my-content">
            <el-input-number v-model="ruleForm.moralAwarded"  :step="1" min="0" controls-position="right" style="width: 100px;"></el-input-number>
          </el-descriptions-item>
        </el-descriptions>
      </el-form-item>
      <el-form-item label="优惠券获得：" prop="couponsAwarded">
        <el-cascader
            v-model="ruleForm.couponsAwarded"
            placeholder="请选择获得优惠券" clearable
            :options="couponsList"
            :props="{ expandTrigger: 'hover' }"></el-cascader>
      </el-form-item>
      <!--開發ing-->
      <el-form-item label="任务地点选择：" prop="isAddLocation" v-show="ruleForm.taskType!=4">
        <el-radio-group v-model="ruleForm.isAddLocation">
          <el-radio label=1>是</el-radio>
          <el-radio label=0>否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="导航功能提供：" prop="isNavigable" v-show="ruleForm.taskType!=4">
        <el-radio-group v-model="ruleForm.isNavigable">
          <el-radio label=1>是</el-radio>
          <el-radio label=0>否</el-radio>
        </el-radio-group>
      </el-form-item>
      <div v-if="ruleForm.taskType === 1">
        <!--拍照打卡类任务 学生是否需要到达指定位置后才能进行拍照打卡 1为需要手机定位 0为不需要手机定位-->
        <el-form-item label="指定位置才能拍照：" prop="isLocation">
          <el-radio-group v-model="ruleForm.isLocation">
            <el-radio label=1>是</el-radio>
            <el-radio label=0>否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="打卡图片要求：" prop="checkinDescription">
          <el-select
              v-model="ruleForm.checkinDescription"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择图片要求">
            <el-option
                v-for="item in itemList"
                :key="item.itemId"
                :label="item.itemName"
                :value="item.itemId">
            </el-option>
          </el-select>
        </el-form-item>
      </div>
      <div v-if="ruleForm.taskType === 4">
        <el-form-item label="题库名：" prop="bankId">
          <el-select v-model="ruleForm.bankId" placeholder="请选择题库" clearable @change="fetchTotalQuestion">
            <el-option
                v-for="item in bankList"
                :key="item.bankId"
                :label="item.bankName"
                :value="item.bankId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="测试题量：" prop="totalQuestions">
          <el-input-number v-model="ruleForm.totalQuestions"  :step="1" min="0" controls-position="right"></el-input-number>
        </el-form-item>
        <el-form-item label="通过测试最低得分：" prop="passingScore">
          <el-input v-model="ruleForm.passingScore" placeholder="请输入通过测试最低得分"></el-input>
        </el-form-item>
        <el-form-item label="考试时长（分钟）：" prop="examDuration">
          <el-input-number v-model="ruleForm.examDuration"  :step="1" min="0" controls-position="right"></el-input-number>
        </el-form-item>
      </div>
      <el-form-item style="text-align: center">
        <el-button type="primary" size="medium" @click="handleNext('ruleForm')" v-show="ruleForm.isAddLocation==1 && ruleForm.taskType!=4">下一步，选择任务地点</el-button>
        <el-button type="primary" size="medium" @click="handleNext('ruleForm')" v-show="ruleForm.isAddLocation==0 || ruleForm.taskType==4">下一步，分配任务</el-button>
        <el-button @click="resetInputForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default{
  name: "couponMonitor",
  data() {
    return{
      ruleForm: {
        taskType:1,
        taskName:'',
        taskSequence: [{
          value: ''
        }],
        isMainQuest:'1',
        taskLabel:'',
        pointsAwarded:0,
        badgeAwarded:'',
        connectionAwarded:0,
        courageAwarded:0,
        luckyAwarded:0,
        wisdomAwarded:0,
        charmAwarded:0,
        healthAwarded:0,
        learningAwarded:0,
        moralAwarded:0,
        couponsAwarded:'',
        isNavigable:'1',
        dateRange:'',
        isLocation:'1',
        totalQuestions:'',
        passingScore:'',
        examDuration:'',
        isAddLocation:'1',
        checkinDescription:'',
        bankId:''

      },
      badgeList:[],
      totalQuestions:0,
      couponsList:[],
      bankList:[],
      itemList:[],
      rules: {
        taskType: [
          { required: true},
        ],
        taskName: [
          { required: true, message: '请输入任务名称', trigger: 'blur' }
        ],
        isMainQuest: [
          { required: true},
        ],
        taskLabel: [
          { required: true, message: '请输入任务标签', trigger: 'blur' }
        ],
        pointsAwarded: [
          { required: true},
        ],
        isNavigable: [
          { required: true},
        ],
        dateRange: [
          { required: true, message: '请选择有效日期', trigger: 'blur'},
        ],
        isLocation: [
          { required: true},
        ],
        totalQuestions: [
          { required: true, message: '请输入测试题量', trigger: 'blur'},
          {
            validator: (rule, value, callback) => {
              if (value < 1 ||value > this.totalQuestions) {
                callback(new Error('测试题量必须为大于零且小于 ' + this.totalQuestions));
              } else {
                callback();
              }
            }
          }
        ],
        passingScore: [
          { required: true, message: '通过测试最低得分不能为空'},
          { pattern: /^[1-9]\d*$/, message: '请输入一个大于 0 的整数', }
        ],
        examDuration: [
          { required: true},
        ],
        isAddLocation: [
          { required: true, message: '请选择任务地点', trigger: 'blur' }
        ],
        checkinDescription: [
          { required: true, message: '请选择图片要求', trigger: 'blur' }
        ],
        bankId: [
          { required: true, message: '请选择题库', trigger: 'blur'},
        ]
      },
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      addInfo:[],

    }

  },
  watch: {
    // 监听type变化
    'ruleForm.taskType': function(newVal, oldVal){
      if (newVal !==  oldVal) {
        this.resetInputForm();
      }
    },
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resetInputForm() {
      this.ruleForm = {
        taskType:this.ruleForm.taskType,
        taskName:'',
        taskSequence: [{
          value: ''
        }],
        isMainQuest:'1',
        taskLabel:'',
        pointsAwarded:0,
        badgeAwarded:'',
        connectionAwarded:0,
        courageAwarded:0,
        luckyAwarded:0,
        wisdomAwarded:0,
        charmAwarded:0,
        healthAwarded:0,
        learningAwarded:0,
        moralAwarded:0,
        couponsAwarded:'',
        isNavigable:'1',
        dateRange:'',
        isLocation:'1',
        totalQuestions:'',
        passingScore:'',
        examDuration:'',
        isAddLocation:'1',
        checkinDescription:'',
        bankId:''
      };
    },
    removeDomain(item) {
      var index = this.ruleForm.taskSequence.indexOf(item)
      if (index !== -1) {
        this.ruleForm.taskSequence.splice(index, 1)
      }
    },
    addDomain() {
      this.ruleForm.taskSequence.push({
        value: '',
        key: Date.now()
      });
    },
    //0.定義試題信息
    addTaskInfo(taskType,taskName,isMainQuest,dateRange,taskLabel,taskSequence,pointsAwarded,
                badgeAwarded,attributesAwarded,couponsAwarded,isNavigable,isLocation,checkinDescription,
                totalQuestions,passingScore,examDuration,bankId){
      return {
        "taskType":taskType,"taskName":taskName, "isMainQuest": isMainQuest, "dateRange": dateRange,
        "taskLabel":taskLabel, "taskSequence":taskSequence, "pointsAwarded": pointsAwarded,
        "badgeAwarded": badgeAwarded, "attributes": attributesAwarded,"couponsAwarded":couponsAwarded,
        "isNavigable":isNavigable,"isLocation":isLocation,"checkinDescription":checkinDescription,
        "totalQuestions":totalQuestions,"passingScore":passingScore,"examDuration":examDuration,"bankId":bankId
      };
    },
    addAttributeInfo(connectionAwarded,courageAwarded,luckyAwarded,wisdomAwarded,charmAwarded,healthAwarded,learningAwarded,moralAwarded){
      return{
        "人脉":connectionAwarded,"勇气":courageAwarded,"幸运":luckyAwarded,"智慧":wisdomAwarded,
        "魅力":charmAwarded,"健康值":healthAwarded,"学习力":learningAwarded,"道德值":moralAwarded
      };
    },
    handleNext(formName){
      let attributeInfo = this.addAttributeInfo(this.ruleForm.connectionAwarded,this.ruleForm.courageAwarded,this.ruleForm.luckyAwarded,this.ruleForm.wisdomAwarded,this.ruleForm.charmAwarded,this.ruleForm.healthAwarded,this.ruleForm.learningAwarded,this.ruleForm.moralAwarded);
      let newArray = this.ruleForm.taskSequence.map(item => item.value);
      let formattedTaskSequence = newArray.map((item, index) => `${index + 1}.${item}`).join("\n"); // 将数组元素格式化为所需的字符串形式
      let checkinDescription = this.ruleForm.checkinDescription;
      let formattedCheckinDescription = "";
      if(checkinDescription.length>0){
        formattedCheckinDescription = checkinDescription.join(',');
      }

      console.log('bankId為:',this.ruleForm.bankId);
      this.addInfo = this.addTaskInfo(this.ruleForm.taskType,this.ruleForm.taskName,this.ruleForm.isMainQuest,this.ruleForm.dateRange,
          this.ruleForm.taskLabel,formattedTaskSequence,this.ruleForm.pointsAwarded,this.ruleForm.badgeAwarded[1],
          attributeInfo,this.ruleForm.couponsAwarded[1],this.ruleForm.isNavigable,this.ruleForm.isLocation,
          formattedCheckinDescription,this.ruleForm.totalQuestions,this.ruleForm.passingScore,this.ruleForm.examDuration,this.ruleForm.bankId)

      console.log("我調用了handleNext",this.addInfo);
      this.$refs[formName].validate((valid) => {
        if (valid && this.ruleForm.isAddLocation==1 && this.ruleForm.taskType!=4) {
          this.$emit('getTaskDetail',this.addInfo);
          this.$emit('nextStep');
        }else if(valid && (this.ruleForm.isAddLocation==0 || this.ruleForm.taskType==4)){
          this.$emit('nextStep');
          this.$emit('nextStep');
        }
        else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration:1000
          });
          return false;
        }
      });
    },

    async saveAdd(){
      let attributeInfo = this.addAttributeInfo(this.ruleForm.connectionAwarded,this.ruleForm.courageAwarded,this.ruleForm.luckyAwarded,this.ruleForm.wisdomAwarded,this.ruleForm.charmAwarded,this.ruleForm.healthAwarded,this.ruleForm.learningAwarded,this.ruleForm.moralAwarded);
      let newArray = this.ruleForm.taskSequence.map(item => item.value);
      let formattedTaskSequence = newArray.map((item, index) => `${index + 1}.${item}`).join("\n"); // 将数组元素格式化为所需的字符串形式
      let checkinDescription = this.ruleForm.checkinDescription;
      let formattedCheckinDescription = checkinDescription.join(',');
      this.addInfo = this.addTaskInfo(this.ruleForm.taskType,this.ruleForm.taskName,this.ruleForm.isMainQuest,this.ruleForm.dateRange,
          this.ruleForm.taskLabel,formattedTaskSequence,this.ruleForm.pointsAwarded,this.ruleForm.badgeAwarded[1],
          attributeInfo,this.ruleForm.couponsAwarded[1],this.ruleForm.isNavigable,this.ruleForm.isLocation,
          formattedCheckinDescription,this.ruleForm.total,this.ruleForm.bankId)
    },
    async getBadgeList() {
      try {
        const res = await axios.get('selectorManage/getBadgeList');

        if (res.status === 200) {
          this.badgeList = res.data.data;
          console.log("badgeList返回值",this.badgeList);
        } else {
          ElMessage('获取徽章数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取徽章数据失败');
      }
    },
    async getCouponsList() {
      try {
        const res = await axios.get('selectorManage/getCouponsList');

        if (res.status === 200) {
          this.couponsList = res.data.data;
          console.log("couponsList返回值",this.couponsList);
        } else {
          ElMessage('获取优惠券数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取优惠券数据失败');
      }
    },
    async getBankList() {
      try {
        const res = await axios.get('/questionBankManage/getBankList');

        console.log("getBankList返回值",res);

        if (res.status === 200) {
          this.bankList = res.data.data;
          console.log("companyList返回值",this.bankList);
        } else {
          ElMessage('获取题库数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取题库数据失败');
      }
    },
    async fetchTotalQuestion() {
      if (this.ruleForm.bankId) {
        const response = await axios.get('/taskManage/getTotalQuestions/'+this.ruleForm.bankId);
        this.totalQuestions = response.data.data;
        console.log("获取題目數量",this.totalQuestions);
      }
    },
    async getItemList() {
      try {
        const res = await axios.get('/selectorManage/getItemList');

        console.log("getBankList返回值",res);

        if (res.status === 200) {
          this.itemList = res.data.data;
          console.log("itemList返回值",this.itemList);
        } else {
          ElMessage('获取打卡图片要求数据失败');
        }
      } catch (error) {
        console.error('Error fetching data:', error);
        ElMessage('获取打卡图片要求数据失败');
      }
    },
  },
  mounted() {
    this.getBadgeList();
    this.getCouponsList();
    this.getBankList();
    this.getItemList();
  }

}
</script>
<style scoped>
:deep(.my-label) {
  background: #ffffff !important;
  border: #ffffff !important;
}
:deep(.my-content) {
  border: #ffffff !important;
}
</style>